package com.zjuh.goodboy.misc;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.zjuh.goodboy.awires.ConfigurationAwire;
import com.zjuh.goodboy.awires.Initializer;
import com.zjuh.goodboy.config.Configuration;
import com.zjuh.goodboy.util.IoUtil;
import com.zjuh.sweet.lang.DateUtil;

public class FileDateRangeManager extends DateRangeManager implements ConfigurationAwire, Initializer {

	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	private File storeFile;
	
	private Configuration configuration;
	
	public FileDateRangeManager(){
	}
	
	public FileDateRangeManager(String fileName){
		setStoreFile(fileName);
	}
	
	public void setStoreFile(String fileName) {
		File f = new File(fileName);
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		storeFile = f;
	}
	
	@Override
	public void init() {
		setStoreFile(configuration.getProperty("date.range.filepath"));
	}

	@Override
	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	protected Date getStoreDate() {
		if (!storeFile.exists()) {
			return null;
		}
		byte[] data;
		try {
			data = IoUtil.readFileData(storeFile);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		if (data == null) {
			return null;
		}
		String dateString = new String(data);
		return DateUtil.parseDate(dateString, DATE_FORMAT);
	}

	@Override
	protected void setNextDate(Date nextDate) {
		String dataString = DateUtil.formatDate(nextDate, DATE_FORMAT);
		try {
			IoUtil.writeFileData(storeFile, dataString.getBytes());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
}
